﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Linq;
using System.ServiceModel;
using System.Text;

namespace Tradex.Connectivity {
    
    /// <summary>
    /// This class hosts and exposes a connector control instance (IConnectorControlApi) via WCF.
    /// </summary>
    public sealed class ConnectorApiHost : IDisposable {

        /// <summary>
        /// Constructor taking all necessary parameters.
        /// </summary>
        /// <param name="control"></param>
        /// <param name="connectorInstanceKey"></param>
        public ConnectorApiHost(IConnectorApi control, string connectorInstanceKey) {
            _ServiceHost = new ServiceHost(control);
            _ServiceHost.AddServiceEndpoint(
                typeof(IConnectorApi),
                new NetNamedPipeBinding(NetNamedPipeSecurityMode.None) { MaxReceivedMessageSize = 65536 * 64 },
                GetConnectorControlUrl(connectorInstanceKey)
            );
            _ServiceHost.Open();
        }

        ServiceHost _ServiceHost;

        /// <inheritdoc />
        public void Dispose() {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        void Dispose(bool disposing) {
            if (disposing) {
                if (_ServiceHost != null) {
                    _ServiceHost.Close();
                    _ServiceHost = null;
                }
            }
        }

        /// <summary>
        /// This method returns the URL of a specific ConnectorName (identified by it's key), in string form. Every
        /// connector key maps to exactly one unique URL, so every connector key can run only once.
        /// </summary>
        /// <param name="connectorKey"></param>
        /// <returns></returns>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings")]
        public static string GetConnectorControlUrl(string connectorKey) {
            if (String.IsNullOrWhiteSpace(connectorKey)) {
                throw new ArgumentException("value can not be null or whitespace", "connectorKey");
            }
            Contract.EndContractBlock();
            string retval = String.Format(CultureInfo.InvariantCulture,
                "net.pipe://localhost/Tradex.Connectivity/{0}ConnectorName/Control.svs",
                connectorKey
            );
            return retval;
        }



    }

}
